package com.suoluo.zenadmin.service.crawler.resolver;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.util.StringUtils;

import com.suoluo.zenadmin.service.crawler.bean.HotelReviewRecordBean;


/**
 * 到到的网页抓取器
 * 
 * @author xiongxu
 * 
 */
class DaoDaoCrawlerResolver extends AbstractCrawlerResolver {

	public DaoDaoCrawlerResolver(CrawlerResovlerTask task) {
		super(task);
	}

	@Override
	protected int resolveReviewCount(Document doc) {
		String reviewCountStr = doc.select("span[property=v:count]").first()
				.text().trim();
		reviewCountStr = reviewCountStr.replaceAll(",", "");
		int reviewCount = Integer.parseInt(reviewCountStr);
		return reviewCount;
	}

	@Override
	protected double resolveReviewScore(Document doc) {
		String str = doc.select("img.sprite-ratings").attr("content").trim();
		double reviewScore = Double.parseDouble(str);
		return reviewScore;
	}

	@Override
	protected double resolveReviewFullScore(Document doc) {
		return 5;
	}

	@Override
	protected String resolveReviewLevel(Document doc) {
		return null;
	}

	@Override
	protected int resolveReviewRank(Document doc) {
		String reviewLevel = doc.select("div.slim_ranking")
				.select("b.rank_text").text();
		return Integer.parseInt(reviewLevel.replaceAll("[^\\d]", "").trim());
	}

	@Override
	protected List<HotelReviewRecordBean> resolveReviewRecords(Document doc) {
		List<HotelReviewRecordBean> list = new ArrayList<HotelReviewRecordBean>();
		Elements eles = doc.select("div#REVIEWS").select("div.reviewSelector");
		Iterator<Element> iter = eles.iterator();
		int temp = 0;

		while (iter.hasNext()) {
			if (temp == 5) {
				break;
			}
			Element ele = iter.next();
			String title = ele.select("div.quote").text();
			String desc = ele.select("p.partial_entry").get(0).ownText();
			// 没有评论直接过滤掉，继续抓取下一条
			if (!StringUtils.hasLength(title) || !StringUtils.hasLength(desc)) {
				continue;
			}

			HotelReviewRecordBean review = new HotelReviewRecordBean();
			review.setRecordTitle(title);
			review.setRecordDesc(desc);
			review.setRecordAutor(ele.select("div.username").text());
			review.setRecordTime(ele.select("span.ratingDate").get(0).ownText());
			String str = ele.select("img.sprite-ratings").attr("content")
					.trim();
			double score = Double.parseDouble(str);
			review.setRecordScore(score);
			review.setRecordFullScore(5.0);
			list.add(review);
			temp++;
		}
		return list;
	}

//	public static void main(String[] args) {
//		CrawlerResovlerTask task = new CrawlerResovlerTask(null);
//		task.setReviewUrl("http://www.daodao.com/Hotel_Review-g298342-d316743-Reviews-LUX_Belle_Mare-Belle_Mare.html");
//		DaoDaoCrawlerResolver r = new DaoDaoCrawlerResolver(task);
//		r.doResolver();
//	}
}
